package com.py.credit.service.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.dao.DeclarationManagementFormDao;
import com.py.credit.entity.Column;
import com.py.credit.entity.DeclarationManagementForm;
import com.py.credit.entity.Table;
import com.py.credit.service.DeclarationManagementFormService;
import com.py.credit.service.excel.read.InspectHandles;
import com.py.credit.utils.SQLBuilder;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.UrlHelper;
import com.py.framework.core.http.HttpAgent;

import io.swagger.models.auth.In;

@Service
public class DeclarationManagementFormServiceImpl implements DeclarationManagementFormService {
	
	@Autowired
    private UrlHelper urlHelper;
	@Autowired
	private DeclarationManagementFormDao declarationManagementFormDao;

	@Override
	public List<DeclarationManagementForm> selectListForPage(Page page, String root_id, String collection_type) {

		return declarationManagementFormDao.selectListForPage(page, root_id, collection_type);
	}

	@Override
	public List<DeclarationManagementForm> selectTable(List<String> list, String tableString) {
		return declarationManagementFormDao.selectTable(list, tableString);
	}

	@Override
	public List<DeclarationManagementForm> selectAllList(String root_id, String collection_type) {
		return declarationManagementFormDao.selectAllList(root_id, collection_type);
	}

	@Override
	public RestServiceResult<List<Object>>  getcube_id_list(String type, String root_id) {
		 String url = urlHelper.getBaseXypjUrl() + "/declarationManagement/selectForPage.json";
	        Map<String, String> params = new HashMap<>(2);
	        params.put("type",type);
	        params.put("root_id",root_id);
	        String result = "";
	        try {
	            // 发送请求
	            result = HttpAgent.getInstance().sendHttpPost(url, params, null);
	            return JSONObject.parseObject(result, new TypeReference<RestServiceResult<List<Object>>>() {
	            });
	        } catch (Exception e) {
	            RestServiceResult<List<Object>> userData = new RestServiceResult<>();
	            userData.setCode(RestServiceResult.CODE_UNKNOW);
	            userData.setMsg("系统异常，请稍后再试！");
	            ExceptionLogger.error(
	                    "远程服务-获取当前用户信息调用异常！(XypjRemoteBaseService#getRolesByUserId) URL:" + url + "Result:" + result,
	                    e.getMessage(), e);
	            return userData;
	        }
	}

	@Override
	public String getcontentId() {
		
		return declarationManagementFormDao.getcontentId();
	}

	@Override
	public Map<String, Object> dataFormatCheck(Object object, List<Map<String, Object>>  listDataMap, Table table, List<Column> columns) {
		 int count = 0;
	        StringBuilder errMsg = new StringBuilder();
	        Map<String, Object> dataFormatError = new HashMap<>(2);
	        String index = "1";
	        int seq = 0;
	        for (Iterator<Map<String, Object>> it = listDataMap.iterator(); it.hasNext(); ) {
	            seq++;
	            //第一步的数据重复校验已判空，不需要进行非空校验
	            Map<String, Object> val = it.next();
	            // 序列
	            index = (null != val.get("rowIndex") ? String.valueOf(val.get("rowIndex")) : String.valueOf(seq));
	            // 整条数据的json
	            String data = JSON.toJSONString(val);
	            StringBuilder error = new StringBuilder();

	            for (Column c : columns) {
	                String code = c.getMetricCode();
	                // 没有值跳过校验
	                if (null == val.get(code) || StringUtils.isBlank(String.valueOf(val.get(code)))) {
	                    continue;
	                }
	                String value = String.valueOf(val.get(code));
	                String name = c.getMetricName();
	                String type = c.getFieldType();
	                if (StringUtils.isNotBlank(value)) {
	                    if (InspectHandles.TYPE_TIMESTAMP.equals(type)) {
	                    	String extend=  "((\\d{2}(([02468][048])|([13579][26]))[\\-]((((0?[13578])|(1[02]))[\\-]((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-]((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-]((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-]((((0?[13578])|(1[02]))[\\-]((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-]((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-]((0?[1-9])|(1[0-9])|(2[0-8]))))))";
	                        // 时间类型不匹配
	                    	Pattern p = Pattern.compile(extend);
	                        Matcher m = p.matcher(value.replace("/", "-"));
	                        boolean dateFlag = m.matches();
	                        if(!dateFlag){
	                        	 error.append("字段" + name + "类型不匹配，应为时间类型;");
	                        }
	                    } else if (InspectHandles.TYPE_NUMBER.equals(type)) {
	                        // 数值类型不匹配
	                        Integer tableId = table.getTableId();
	                        if (210000 == tableId || 210001 == tableId || 210002 == tableId || 210003 == tableId) {
	                            Matcher m = InspectHandles.NUMBER_PATTERN_DOUBLE_PUBLICITY.matcher(value);
	                            if (!m.matches()) {
	                                error.append("字段" + name + "类型不匹配，应为最多六位小数的数值类型;");
	                            }
	                        }
//	                        else {
//	                            Matcher m = InspectHandles.NUMBER_PATTERN.matcher(value);
//	                            if (!m.matches()) {
//	                                error.append("字段" + name + "类型不匹配，应为最多两位小数的数值类型;");
//	                            }
//	                        }
	                    } else {
	                        int length = c.getFieldLength();
	                        // 字段长度超长
	                        if (value.length() > length) {
	                            error.append("字段" + name + "长度超过数据表长度;");
	                        }
	                    }
	                }
	            }
	}
			return dataFormatError;
	}

	@Override
	public void addApplication(String datatype, String dept, String cube_id, String datapath,String yjpath,String mainType) {
		declarationManagementFormDao.addApplication(datatype,dept,cube_id,datapath,yjpath,mainType);
		
	}

	@Override
	public List<LinkedHashMap<String, Object>> selectByConditionForPage(Integer shzt,String mainType, String tablename,
			String mainName,  List<String> columns, String[] additionalColumns, String conditionStr,
			Page page) {
		List<String> conditions = SQLBuilder.createConditionSql(conditionStr);
		Map<String, String> params = new HashMap<>();
		params.put("tablename", tablename);
		params.put("mainName", mainName);
		params.put("shzt", String.valueOf(shzt));
		params.put("mainType", mainType);
		List<LinkedHashMap<String, Object>> ModifyLogs = declarationManagementFormDao.selectByConditionForPage(params, columns,
				additionalColumns, conditions, page);

		return ModifyLogs;
	}

	@Override
	public void updateApplication(String id, String shjg, String shyj, String shdept, String shr) {
		declarationManagementFormDao.updateApplication(id,shjg,shyj,shdept,shr);
		
	}

	@Override
	public List<Map<String, Object>> webSelectHistoryForPage(Page page) {
		
		return declarationManagementFormDao.webSelectHistoryForPage(page);
	}

	
	/* (非 Javadoc)
	 *
	 
	 *
	 
	 * @param sblb
	 * @param sbrq
	 * @param ztlx
	 * @param page
	 * @return
	 * @see com.py.credit.service.DeclarationManagementFormService#selectZzsbTableListForPage(java.lang.String, java.lang.String, java.lang.String, com.py.framework.core.common.Page)
	 */
	
	@Override
	public List<LinkedHashMap<String, Object>> selectZzsbTableListForPage(String sblb,  String ztlx,
			Page page) {
		
		return declarationManagementFormDao.selectZzsbTableListForPage(sblb,ztlx,page);
	}
}
